// pages/timetable/timetable.js
var app=getApp();
var util=require("../../utils/util");
var other=require("../../utils/other");
var table=require("../../api/table");
var my=require("../../api/my");


Page({
  data: {
    height: wx.getSystemInfoSync().windowHeight,
    width: wx.getSystemInfoSync().windowWidth,
    statusBarHeight: wx.getSystemInfoSync().statusBarHeight,
    capsuleHeight: 44,
    navColor: 'rgba(0,0,0,0)',
    title: '课程表',
    textColor: '#fff',
    year: '',
    timeStar: '',
    timeEnd: '',
    mealName: '',
    show_page: 0,
    value: [0,0],
    baby_list: [],
    cour_list: [],
    time_list: [],
    table_list: [],
    login: true,
    token: '',
    userinfo: '',
    pop_show: true,
    stars:[1,2,3,4,5],
    star_index: 0,
    score: "0.0",
    com_text: '',
    inst_show: true,
    inst_index: 0,
    baby_index: 0,
    cour_index: 0,
    time_index: 0,
    table_index: '',
    currentPage: 1,
    pageSize: 10,
    hasMoreDate: true,
    check_on: false,
    show_nav: false,
    focus: false,
    place_text: '大家都在问"环境怎么样?""课程效果怎么样?""课程性价比怎么样?""老师优秀吗?""位置好找吗?""好停车吗?"'
  },
  // 监听页面加载
  onLoad: function (options) {
    var that=this;
    var isIphone=wx.getSystemInfoSync().system.indexOf("Android")>-1?false:true;
    var month=new Date().getMonth()+1,year=new Date().getFullYear();
    var curWidth=(that.data.width-30)/6,moveWidth=(month-2)*curWidth;
    if(moveWidth>0){
      that.setData({scrollLeft:moveWidth})
    }else{
      that.setData({scrollLeft:0})
    }
    var timeStar = new Date(year, month-1, 1).getTime(),timeEnd = new Date(year, month, 1).getTime();
    var obj = other.dateTimePicker(2018,year);
    that.setData({year:year,month:month>=10?month:'0'+month,timeStar:timeStar,timeEnd:'',time_index:month-1,time_list:obj.dateTimeArray,isIphone:isIphone})
    that.now_time(obj);
    wx.getStorage({
      key: 'userinfo',
      success:function(res){
        var userinfo=res.data;
        that.get_baby_list(userinfo.id)
      }
    })
  },
  // 当前时间
  now_time:function(obj){
    var that=this,year=that.data.year,month=that.data.month,value=that.data.value;
    var time=obj.dateTimeArray;
    for(var i=0;i<time[0].length;i++){
      if(time[0][i]==year){
        value[0]=i
      }
    }
    for(var j=0;j<time[1].length;j++){
      if(time[1][j]==month){
        value[1]=j
      }
    }
    that.setData({value:value});
  },
  // 选择时间
  picker_change_time:function(e){
    var that = this;
    var val = e.detail.value;
    that.setData({value: val})
  },
  confirm_time:function(){
    var that=this,time_list=that.data.time_list,value=that.data.value,baby_list=that.data.baby_list,baby_index=that.data.baby_index,cour_list=that.data.cour_list,cour_index=that.data.cour_index;
    var year=time_list[0][value[0]],month=Number(time_list[1][value[1]].replace(/^0/, ''));
    var timeStar = new Date(year, month-1, 1).getTime(),timeEnd = new Date(year, month, 1).getTime();
    that.setData({timeStar:timeStar,timeEnd:timeEnd,currentPage:1,table_list:[],year:year,month:time_list[1][value[1]]})
    that.close_pop();
    if(baby_list.length==0){
      util.page_show_toast('请先添加宝宝',1500);
      return false;
    }
    if(cour_list.length==0){
      util.page_show_toast('请先为宝宝购买课程',1500);
      return false;
    }
    that.setData({show_nav:false})
    //
    that.get_cour_table(baby_list[baby_index].id,cour_list[cour_index].setMealId,timeStar,timeEnd);
  },
  // 弹窗
  close_pop:function(){
    this.setData({pop_show:!this.data.pop_show})
    wx.showTabBar({animation: true})
  },
  open_pop:function(e){
    var that=this;
    var num=e.currentTarget.dataset.num;
    if(num==1){
      that.setData({pop_show:!that.data.pop_show,show_page:num})
    }else{
      var cid=e.currentTarget.dataset.cid,did=e.currentTarget.dataset.did,index=e.currentTarget.dataset.index;
      that.setData({pop_show:!that.data.pop_show,show_page:num,cid:cid,did:did,table_index:index,star_index:0,score:"0.0",com_text:''})
    }
    wx.hideTabBar({animation: true})
  },
  close_inst:function(){
    this.setData({inst_show:!this.data.inst_show,textColor:'#fff',navColor:'rgba(0,0,0,0)'})
  },
  open_inst:function(e){
    var that=this,index=e.currentTarget.dataset.index;
    that.setData({inst_show:!that.data.inst_show,inst_index:index,textColor:'#424752',navColor:'#fff'})
  },
  return:function(){},
  // 跳转
  nav_getpage:function(e){
    var that=this;
    var index=e.currentTarget.dataset.index;
    if(index==1){
      wx.navigateTo({
        url: '../login/login',
      })
    }else if(index==2){
      that.close_inst()
      wx.switchTab({
        url: '../home/home',
      })
    }
  },
  add_baby:function(){
    var that=this,userinfo=that.data.userinfo;
    wx.navigateTo({
      url: '../../mypage/addBady/addBaby?id='+userinfo.id,
    })
    that.close_inst()
  },
  nav_home:function(){
    wx.switchTab({
      url: '../home/home',
    })
  },
  // 请假
  nav_leave:function(e){
    var that=this,baby_list=that.data.baby_list,baby_index=that.data.baby_index;
    var did=e.currentTarget.dataset.id,index=e.currentTarget.dataset.index,cid=baby_list[baby_index].id,name=baby_list[baby_index].name;
    that.setData({table_index:index})
    wx.navigateTo({
      url: '../../timetable/forLeave/forLeave?did='+did+'&cid='+cid+'&name='+name,
    })
  },
  // 选择宝宝或者课程
  check_item:function(e){
    var that=this,baby_list=that.data.baby_list,cour_list=that.data.cour_list,baby_index=that.data.baby_index,cour_index=that.data.cour_index,timeStar=that.data.timeStar,timeEnd=that.data.timeEnd,check_on=that.data.check_on;
    var type=e.currentTarget.dataset.type,index=e.currentTarget.dataset.index,id=e.currentTarget.dataset.id;
    if(type==1){
      if(baby_index!=index){
        that.setData({baby_index:index,cour_list:[],table_list:[],currentPage:1,show_nav:false})
        that.get_baby_cour(id)
        that.close_inst()
      }
    }else{
      if(cour_index!=index||check_on){
        that.setData({cour_index:index,mealName:cour_list[index].courseName,currentPage:1,table_list:[],check_on:false,show_nav:false})
        that.get_cour_table(baby_list[baby_index].id,id,timeStar,timeEnd);
        that.close_inst()
      }
    }
  },
  // 全选课程
  check_all:function(){
    var that=this,baby_list=that.data.baby_list,baby_index=that.data.baby_index,cour_list=that.data.cour_list,cour_index=that.data.cour_index,timeStar=that.data.timeStar,timeEnd=that.data.timeEnd,check_on=that.data.check_on;
    if(!check_on){
      that.setData({mealName:"所有课程",currentPage:1,table_list:[],check_on:true})
      that.get_cour_table(baby_list[baby_index].id,cour_list[cour_index].setMealId,timeStar,timeEnd);
      that.close_inst()
    }else{
      that.setData({mealName:cour_list[cour_index].courseName,currentPage:1,table_list:[],check_on:false})
      that.get_cour_table(baby_list[baby_index].id,cour_list[cour_index].setMealId,timeStar,timeEnd);
      that.close_inst()
    }
  },
  // 下拉刷新
  onPullDownRefresh:function(){
    // wx.startPullDownRefresh()
    var that=this,userinfo=that.data.userinfo;
    that.init_table();
    // 刷新
    setTimeout(()=>{
      wx.stopPullDownRefresh()
    },500)
    that.get_baby_list(userinfo.id)
  },
  init_table:function(){
    var that=this;
    that.setData({
      mealName: '',
      baby_list: [],
      cour_list: [],
      table_list: [],
      baby_index: 0,
      cour_index: 0,
      table_index: '',
      currentPage: 1,
      check_on: false,
      show_nav: false
    })
  },
  // 刷新
  onShow:function(){
    var that=this,table_list=that.data.table_list,table_idnex=that.data.table_index;
    var info=wx.getStorageSync('unionId'),token=wx.getStorageSync('token'),login_info=wx.getStorageSync('login_info'),userinfo=wx.getStorageSync('userinfo');
    if((info&&token)||(login_info&&token)){
      that.setData({login:true,token:token,textColor:'#fff',userinfo:userinfo})
    }else{
      that.setData({login:false,textColor: '#424752'})
    }
    if(app.globalData.login||app.globalData.change_table||app.globalData.change_baby){
      that.get_baby_list(userinfo.id)
      app.globalData.login=false;
      app.globalData.change_table=false;
      app.globalData.change_baby=false;
    }
    if(app.globalData.set_leave){
      table_list[table_idnex].status=3;
      that.setData({table_list:table_list});
      app.globalData.set_leave=false;
    }
  },
  // 触底
  scroll_bottom:function(){
    var that=this,hasMoreData=that.data.hasMoreData,baby_list=that.data.baby_list,baby_index=that.data.baby_index,cour_list=that.data.cour_list,cour_index=that.data.cour_index,timeStar=that.data.timeStar,timeEnd=that.data.timeEnd;
    if(hasMoreData){
      that.get_cour_table(baby_list[baby_index].id,cour_list[cour_index].setMealId,timeStar,timeEnd);
    }else{
      util.page_show_toast('没有更多课表了',1500);
    }
  },
  // 评价
  check_fen:function(e){
    var that = this;
    var index = e.currentTarget.dataset.index;
    that.setData({star_index:(index+1),score:String((index+1).toFixed(1))})
  },
  input_focus:function(){
    var that=this;
    setTimeout(()=>{that.setData({focus:true})},500)
  },
  input_blur:function(){
    this.setData({focus:false})
  },
  input_val:function(e){
    this.setData({com_text: e.detail.value})
  },
  confirm_com:function(){
    var that=this,score=parseInt(that.data.score),text=that.data.com_text,testSpace = /^[ ]*$/g;
    if(score==0){
      util.page_show_toast('请先评分',1500);
      return false;
    }
    if(!text||testSpace.test(text)){
      util.page_show_toast('请填写评价',1500);
      return false;
    }
    that.add_comment(score,text)
  },
  // 宝宝列表
  get_baby_list:function(uid){
    wx.showLoading({title:"加载中"})
    var that=this;
    my.get_baby_list({parentId:uid}).then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        if(list.length > 0){
          for(var i=0;i<list.length;i++){
            list[i].birthday=util.formatTime_age(new Date(list[i].birthday))
            var num = (new Date().getFullYear() - new Date(list[i].birthday).getFullYear())>0?(new Date().getFullYear() - new Date(list[i].birthday).getFullYear()):1;
            list[i].age=util.convertToChinaNum(num)+"岁";
          }
          that.get_baby_cour(list[0].id)
        }else{
          that.setData({show_nav:true})
        }
        that.setData({baby_list: list})
      }
    })
  },
  // 宝宝购买课程列表
  get_baby_cour:function(id){
    var that=this,timeStar=that.data.timeStar,timeEnd=that.data.timeEnd,token=that.data.token;
    table.get_baby_cour({"childId":id},token).then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        if(list.length>0){
          that.setData({cour_list: list,mealName:list[0].courseName,currentPage:1})
          //
          that.get_cour_table(id,list[0].setMealId,timeStar,timeEnd)
        }else{
          that.setData({cour_list: [],table_list:[],mealName:'',currentPage:1,show_nav:true})
        }
      }
    })
  },
  // 查询课程课表
  get_cour_table:function(cid,sid,star,end){
    wx.showLoading({title: '加载中'})
    var that=this,currentPage=that.data.currentPage,pageSize=that.data.pageSize,token=that.data.token,check_on=that.data.check_on;
    var params={
      "currentPage": currentPage,
      "pageSize": pageSize,
      "childId": cid,
      "courseBeginTime": star,
      "courseEndTime": end,
      "setMealId": check_on?'':sid
    }
    // if(!end){delete params.courseEndTime}
    table.get_cour_table(params,token).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.records;
        for(var i=0;i<list.length;i++){
          list[i].month_time= util.formatTime_month_else(new Date(list[i].courseBeginTime))
          list[i].week=util.getweekday(util.formatTime_age(new Date(list[i].courseBeginTime)))
          list[i].start=util.formatTime_time(new Date(list[i].courseBeginTime))
          list[i].end=util.formatTime_time(new Date(list[i].courseEndTime))
          list[i].teachName=list[i].teachName?(list[i].teachName.indexOf("老师")>-1?list[i].teachName.split("老师")[0]:list[i].teachName):''
        }
        var table_list = that.data.table_list;
        table_list = util.extend(table_list, list)
        if (list.length < pageSize) {
          that.setData({
            table_list: table_list,
            hasMoreData: false
          })
        } else {
          that.setData({
            table_list: table_list,
            hasMoreData: true,
            currentPage: currentPage + 1
          })
        }
        if(list.length==0&&table_list.length==0){
          that.setData({show_nav:true})
        }
      }
    })
  },
  // 添加课程评价
  add_comment:function(score,text){
    var that=this,token=that.data.token,cid=that.data.cid,did=that.data.did,table_list=that.data.table_list,table_index=that.data.table_index;
    var params={
      "scheduleCourseId": cid,
      "content": util.removeAllSpace(text),
      "score": score,
      "scheduleDetailId": did
    }
    table.add_comment(params,token).then(res=>{
      if(res.data.code==200){
        that.close_pop()
        util.page_show_toast('提交成功',1500);
        table_list[table_index].status=5;
        that.setData({table_list:table_list,star_index:0,score:"0.0",com_text:''})
      }
    })
  },
})